// @Description	"GUI输出Gin的路由层"
// @Author  Yang
// @Date  2025/11/27 11:05 AM

package lib

import (
	"fmt"
	"sort"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// 颜色
const (
	blue   = "\033[34m"
	green  = "\033[32m"
	yellow = "\033[33m"
	cyan   = "\033[36m"
	reset  = "\033[0m"
)

// printBanner
// @Description: 打印彩色 Banner
// @Author yang 2025-11-27 11:12:18
func printBanner() {
	timestamp := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(blue + "╔════════════════════════════════════════════════╗" + reset)
	fmt.Printf("║  %s🚀  Gin Routes Overview (%s)%s  ║\n", cyan, timestamp, reset)
	fmt.Println(blue + "╚════════════════════════════════════════════════╝" + reset)
	fmt.Println()
}

// detectGroup
// @Description:  根据完整 path 检测 group（取前两级目录）
// @Author yang 2025-11-27 11:12:31
// @Param path
// @Return string
func detectGroup(path string) string {
	if path == "/" {
		return "/"
	}
	parts := strings.Split(path, "/")
	if len(parts) >= 3 {
		return "/" + parts[1] + "/" + parts[2]
	} else if len(parts) == 2 {
		return "/" + parts[1]
	}
	return "/"
}

// PrintRoutesPretty
// @Description:  美观打印全部路由（含 Handler）
// @Author yang 2025-11-27 11:12:55
// @Param r
func PrintRoutesPretty(r *gin.Engine, hideModule []string) {
	printBanner()

	routes := r.Routes()

	// Module -> Controller -> []RouteInfo
	modules := map[string]map[string][]gin.RouteInfo{}

	for _, rt := range routes {
		// path 拆分
		parts := strings.Split(rt.Path, "/")
		module := "root"
		controller := "root"
		if len(parts) >= 2 {
			module = parts[1] // 第一级作为模块
		}
		if len(parts) >= 3 {
			controller = parts[2] // 第二级作为 controller
		}

		if _, ok := modules[module]; !ok {
			modules[module] = map[string][]gin.RouteInfo{}
		}
		modules[module][controller] = append(modules[module][controller], rt)
	}

	// module 排序
	moduleKeys := make([]string, 0, len(modules))
	for m := range modules {
		moduleKeys = append(moduleKeys, m)
	}
	sort.Strings(moduleKeys)

OuterLoop:
	for _, m := range moduleKeys {
		for _, v := range hideModule {
			if m == v {
				continue OuterLoop
			}
		}

		fmt.Printf("%s◈ Module: %s%s\n", blue, m, reset)
		// controller 排序
		controllerKeys := make([]string, 0, len(modules[m]))
		for c := range modules[m] {
			controllerKeys = append(controllerKeys, c)
		}
		sort.Strings(controllerKeys)

		for _, c := range controllerKeys {
			fmt.Printf("   └─ Controller: %s\n", c)

			// route 排序
			routesList := modules[m][c]
			sort.Slice(routesList, func(i, j int) bool {
				return routesList[i].Path < routesList[j].Path
			})

			for _, rt := range routesList {
				fmt.Printf("       ├─ %s%-7s%s %s\n", green, rt.Method, reset, rt.Path)

				// Handler 美化
				handler := strings.TrimPrefix(rt.Handler, "github.com/")
				handler = strings.TrimPrefix(handler, "golang-manage-admin/")
				//fmt.Printf("           %s%-10s%s %s\n", yellow, "handler:", reset, handler)
			}
		}
		fmt.Println()
	}
}
